Golang : Get remaining text such as id or filename after last segment in URL path
Problem:
Retrieving the last segment/part or the remaining text after a slash in the URL or filename in a path can be challenging for newbies in programming. Such as:
123456
from //www.socketloop.com/123456
or
image.png
from c:\windows\image.png
How to extract the desired information from an URL or file path?
Solution:
This is known as extracting the base of a URL or file path. Use the path
package base()
function to extract the last segment or remaining text after the last slash.
Here you go!
package main
import (
"fmt"
"path"
"path/filepath"
)
func main() {
url := "http://www.abcdef.com/12345678"
base := path.Base(url)
fmt.Println(base)
// NOTE: filepath.Base() will WORK with `\`
// provided this program runs on Windows platform
// if this program executes on Non-windows or play.golang.org
// it will show the entire string instead of
// the desire image.exe
// IT IS NOT A BUG!
windowsFilePath := `c:\windows\image.exe`
imageFile := filepath.Base(windowsFilePath)
fmt.Println(imageFile)
}
Output:
12345678
image.exe
See also : Golang : Match strings by wildcard patterns with filepath.Match() function
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7k Golang : Get environment variable
+7.3k Golang : Process json data with Jason package
+11.2k Golang : How to flush a channel before the end of program?
+14.4k Golang : How to get URL port?
+13.4k Golang : Get user input until a command or receive a word to stop
+6.8k Golang : constant 20013 overflows byte error message
+13.2k Golang : Read from buffered reader until specific number of bytes
+6k Golang : Debug with Godebug
+33.8k Golang : Create x509 certificate, private and public keys
+26.5k Golang : How to check if a connection to database is still alive ?
+6.1k Javascript : Generate random key with specific length
+21k Golang : Convert(cast) string to rune and back to string example